//
//  HeartView.swift
//  Tiktok
//
//  Created by xmd on 10/23/20.
//

import SwiftUI
import Lottie

struct LikeButton: View {
    @EnvironmentObject var model: VideoPlayerPageVM
    @State var isLiked: Bool = false

    
    var body: some View {
        LikeButtonHost(isLiked: $isLiked)
            .onReceive(model.$isLiked) { isLiked in
                self.isLiked = isLiked
            }
    }
}

struct LikeButtonHost: UIViewRepresentable {
    @Binding var isLiked: Bool
    
    func makeUIView(context: Context) -> some UIView {
        return LottieView()
    }
    func updateUIView(_ uiView: UIViewType, context: Context) {
        
    }
    func makeCoordinator() -> Coordinator {
        return Coordinator(self)
    }
}

class Coordinator {
    var parent: LikeButtonHost
    
    init(_ parent: LikeButtonHost) {
        self.parent = parent
    }
}

class LottieView: UIView {
    let lottieView = AnimatedSwitch()
    var isLiked = false
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        lottieView.animation = .named("th4")
        lottieView.translatesAutoresizingMaskIntoConstraints = false
        lottieView.setIsOn(isLiked, animated: false)
        lottieView.setProgressForState(fromProgress: 0, toProgress: 1, forOnState: true)
        
        let tap = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:)))
        lottieView.addGestureRecognizer(tap)
        self.addSubview(lottieView)
        NSLayoutConstraint.activate([
            lottieView.centerXAnchor.constraint(equalTo: self.centerXAnchor),
            lottieView.widthAnchor.constraint(equalToConstant: 50),
            lottieView.heightAnchor.constraint(equalToConstant: 50)
        ])
    }
    
    @objc func handleTap(_ sender: UITapGestureRecognizer? = nil) {
        isLiked.toggle()
        lottieView.setIsOn(isLiked, animated: true)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
